import {
  XhrError,
  XhrErrorType,
  XhrRequestConfig,
  XhrResponse
} from "ajax-hook";
import Yssoa from "./index";

/**
 * This interface can be augmented by users to add types to Koa's default state
 */

type DefaultState<T> = { [P in keyof T]: T[P] };

export interface IContextInfo<T = any> {
  req: XhrRequestConfig;
  res: XhrResponse;
  err: XhrError | null;
  hasError: boolean;
  app: Yssoa;
  state: Partial<DefaultState<T>>; // 中间件会把数据放入State
}

export default class Context<T = any> implements IContextInfo<T> {
  private reason: XhrError | null = null;
  public state: Partial<DefaultState<T>> = {};

  constructor(
    public req: XhrRequestConfig,
    public res: XhrResponse,
    public readonly app: Yssoa
  ) {
  }

  get err(): XhrError {
    return this.reason!;
  }

  get hasError() {
    return this.reason != null;
  }

  Error(type: XhrErrorType) {
    this.reason = {
      type: type,
      config: this.req
    };
  }
}
